from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from book.models import BookInfo
from book.serializers_2 import BookSerializer, BookSerializerForRead


class BooksViewSet(GenericViewSet):
    queryset = BookInfo.objects.all()

    def list(self, request):
        books = self.get_queryset()
        ser = self.get_serializer(books, many=True)
        return Response(ser.data)

    def create(self, request):
        book = self.get_serializer(data=request.data)
        book.is_valid(raise_exception=True)
        book.save()
        return Response(book.data)

    def get_serializer_class(self):
        if self.action == 'list':
            return BookSerializerForRead
        elif self.action == 'create':
            return BookSerializer


class BookViewSet(GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def retrieve(self, request, pk):
        book = self.get_object()
        book = BookSerializer(book)
        return Response(book.data)

    def update(self, request, pk):
        book = self.get_object()
        serializer = BookSerializer(book, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.validated_data)

    def destroy(self, request, pk):
        book = self.get_object()
        book.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
